//index.js
//获取应用实例
const app = getApp(),
  globalData = app.globalData,
  api = require('../../api/index'),
  http=require('../../utils/http'),
  utils = require('../../utils/util');

Page({
  data: {
    attention:true,//是否关注公众号 
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    imageBaseUri: globalData.imageBaseUri,
    mActive: 0,
    pay_video_list:[],
   
    navicon: "",
    banner: {
      data: [],
      autoplay: true,
      interval: 3000,
      duration: 1000,
      currentSwiper: 0,
    },
    toast: {
      visible: false,
      text: ''
    },
    status: 0,
    giftData: {},
    coupons: [],
    popularList: [], // 人气榜单
    getGiftList: [], // 黑标产品（门槛礼包）
    skinList: [], // 皮肤管理师
    healtyList: [], // 健康态
    youthList: [], // 年轻态
    filter: {
      keywords: "",
      brandId: "",
      categoryId: "",
      types: [], // 1 人气 2 黑标 
      goodsOnState: 1,
      goodsSortByEnum: 1,
      currenetPageIndex: 1,
      pageSize: 10,
      recordCount: 0
    },
    filter2: {
      currenetPageIndex: 1,
      pageSize: 10,
      recordCount: 0
    },
    _image: true,
    list: []
  },
  onLoad: function (options) {
    wx.setStorage({
      key: "isLoginPage",
      data: false
    })
    if (options.userId) {
      wx.setStorageSync('inviteId', options.userId)
    }
    console.log('分享进入', options.userId, 'userid', wx.getStorageSync('inviteId'), 'inviteId')
    this.reload();

  },
  reload() {
    this.setData({
      status: 0
    });
    // 是否关注公众号
    // this.attention()
    this.getIndexList()
    this.getIndexBanner();
    this.getNewerGiftBanner();
    // 优惠卷
    this.getTwoCoupons();
    this.getPopBanner();
    this.getBlackBanner();
    this.getSkinBanner();
    this.getPopularList();
    this.getHealthList();
    this.getYouthList();
    this.getGiftList();
    this.getDoctors();
    this.getGroupList();
    this.vido_pay()
    // 活动
    this.activityList()
  },

  activityList(){
    http.request("GET","/Activity/ActivityMenu").then((res)=>{
        console.log(res);
        this.setData({
            navicon:res.data.ResData
        })
    })
  },
//   是否关注公众号
    attention(){
      http.request("GET","/user/follow_wechat").then((res)=>{
          console.log(res);
          if(res.data.ResData.is_follow){
              this.setData({
                attention:false
              })
          }else{
              this.setData({
                  attention:true
              })
          }
      })
    },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * swiper切换
   */
  swiperChange(e) {
    this.setData({
      'banner.currentSwiper': e.detail.current
    })
  },
  toDetail(e) {
    wx.navigateTo({
      url: `/pages/product/detail/detail?id=${e.currentTarget.dataset.id}`,
    })
  },
  tabChange(e) {
    console.log('tab change', e)
  },
  toList(e) {
    let type = e.currentTarget.dataset.type;
    switch (type) {
      case '1': // 人气榜单商品列表
        wx.navigateTo({
          url: '/pages/product/list/list?type=1',
        })
        break;
      case '2': // 黑标商品列表
        wx.navigateTo({
          url: '/pages/product/list/list?type=2',
        })
        break;
      case '3': // 皮肤管理师列表
        wx.navigateTo({
          url: '/pages/skin/list/list?type=3',
        })
        break;
      case '2021082220364868299243': // 健康态
        wx.navigateTo({
          url: `/pages/product/list/list?id=${type}`,
        })
        break;
      case '2021082220285313243384': // 年轻态
        wx.navigateTo({
          url: `/pages/product/list/list?id=${type}`,
        })
        case '2022070517071882559540': // 技术产品服务
        wx.navigateTo({
          url: `/pages/product/list/list?id=${type}`,
        })
        break;
      default:
        return;
    }

  },
  toSkinDetail(e) {
    wx.navigateTo({
      url: `/pages/skin/detail/detail?id=${e.currentTarget.dataset.id}`,
    })
  },
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  toApply(e) {
    wx.navigateTo({
      url: `/pages/apply/apply?id=${e.currentTarget.dataset.id}`,
    })
  },
  goMore(e){
    console.log(e)
    let type = e.currentTarget.dataset.item.id
    wx.navigateTo({
      url: `/pages/product/list/list?id=${type}`,
    })
  },

  async getIndexList(){
    try {
      let res = await api.goods.getIndexGood()
      console.log(res,123456)
      this.setData({
        list: res.data.ResData || []
      })
    } catch (e) {
      console.log(e, '获取列表失败')
    }
  },

 
  // 获取首页banner
  async getIndexBanner() {
    try {
      let res = await api.banner.getBanners('home_banner'),
        data = res.data.ResData || [];
      console.log(res, 'banners')
      this.setData({
        status: 2,
        'banner.data': data
      })
    } catch (e) {
      console.log(e, '获取首页banner失败')
      this.setData({
        status: 2
      })
    }
  },

  // 获取新人优惠券礼包
  async getNewerGiftBanner() {
    try {
      let res = await api.banner.getLatestBanner('home_giftbag'),
        data = res.data.ResData || {};
      this.setData({
        giftData: data
      })
      console.log(res, 'gift banenr ')
    } catch (e) {
      console.log(e, '获取首页礼包失败')
    }
  },

  // 获取优惠券2个
  async getTwoCoupons() {
    try {
      let res = await api.coupon.getLatestCoupon(2),
        data = res.data.ResData || [];
      console.log(res, '优惠券')
      this.setData({
        coupons: data
      })
    } catch (e) {
      console.log(e, '获取优惠券失败')
    }
  },

  // 领取优惠券
  async getCoupon(e) {
    if (!utils.getLoginState()) {
      return utils.checkLoginState({
        routeUri: 3,
        uri: '/pages/index/index'
      });
    }
    let id = e.currentTarget.dataset.id;
    try {
      let res = await api.coupon.receiveCoupon({
        couponId: id
      });
      console.log(res, '领取优惠券')
      this.setData({
        toast: {
          visible: true,
          text: '领取成功'
        }
      })
    } catch (e) {
      console.log(e, '领取优惠券失败')
      this.setData({
        toast: {
          visible: true,
          text: e.data.ErrMsg
        }
      })
    }
  },

  // 获取人气榜单标题
  async getPopBanner() {
    try {
      let res = await api.banner.getBanners('home_popular'),
        data = res.data.ResData || [];
      console.log(res, 'banners')
      this.setData({
        status: 2,
        popular: data
      })
    } catch (e) {
      console.log(e, '获取首页banner失败')
      this.setData({
        status: 2
      })
    }
  },

  // 获取黑标商品标题图片
  async getBlackBanner() {
    try {
      let res = await api.banner.getBanners('home_gift'),
        data = res.data.ResData || [];
      console.log(res, 'banners')
      this.setData({
        status: 2,
        black: data
      })
    } catch (e) {
      console.log(e, '获取首页banner失败')
      this.setData({
        status: 2
      })
    }
  },

  // 获取服务人员图片
  async getSkinBanner() {
    try {
      let res = await api.banner.getBanners('home_skin'),
        data = res.data.ResData || [];
      console.log(res, 'banners')
      this.setData({
        status: 2,
        skin: data
      })
    } catch (e) {
      console.log(e, '获取首页banner失败')
      this.setData({
        status: 2
      })
    }
  },

  // 获取人气商品列表
  async getPopularList() {
    this.setData({
      "filter.types": [1, 3],
      "filter.categoryId": "2022070517074053836446"
    })
    try {
      let res = await api.goods.getGoodsPages(this.data.filter),
        data = res.data.ResData.Items || [];

      data.map(item => {
        if (item.MarketingTypes.toString().indexOf('2') != -1) {
          item.isSeckill = true;
        } else {
          item.isSeckill = false;
        }
        if (item.MarketingTypes.toString().indexOf('3') != -1) {
          item.isGroup = true;
        } else {
          item.isGroup = false;
        }
      })

      this.setData({
        popularList: data.splice(0, 7)
      })
      console.log(res, '商品列表', this.data.popularList)
    } catch (e) {
      console.log(e, '获取人气列表失败')
    }
  },
  async vido_pay() {
    try {
      let res = await api.user.pay_video()
      console.log(res,'视频')
      this.setData({
        pay_video_list:res.data.ResData.Items
      })
    } catch (e) {
      console.log(e, '获取视频失败')
    }
  },

  // 获取黑标产品列表
  async getGiftList() {
    this.setData({
      "filter.types": [2],
      "filter.categoryId": "2020082714043175795656"
    })
    try {
      let res = await api.goods.getGoodsPages(this.data.filter),
        data = res.data.ResData.Items || [];

      data.map(item => {
        if (item.MarketingTypes.toString().indexOf('2') != -1) {
          item.isSeckill = true;
        } else {
          item.isSeckill = false;
        }
        if (item.MarketingTypes.toString().indexOf('3') != -1) {
          item.isGroup = true;
        } else {
          item.isGroup = false;
        }
      })

      this.setData({
        getGiftList: data.splice(0, 3)
      })
      console.log(res, '黑标商品列表')
    } catch (e) {
      console.log(e, '获取黑标商品列表失败')
    }
  },

  // 获取健康态列表
  async getHealthList() {
    this.setData({
      "filter.categoryId": '2022070517072482067285'
    })
    try {

      try {
        let res = await api.goods.getGoodsPages(this.data.filter),
          data = res.data.ResData.Items || [];

        data.map(item => {
          if (item.MarketingTypes.toString().indexOf('2') != -1) {
            item.isSeckill = true;
          } else {
            item.isSeckill = false;
          }
          if (item.MarketingTypes.toString().indexOf('3') != -1) {
            item.isGroup = true;
          } else {
            item.isGroup = false;
          }
        })

        this.setData({
          healtyList: data.splice(0, 6)
        })
        console.log(res, '健康态商品列表')
      } catch (e) {
        console.log(e, '获取健康态列表失败')
      }
    } catch (e) {
      console.log(e, '获取健康态列表失败')
    }
  },

  // 获取年轻态
  async getYouthList() {
    this.setData({
      "filter.categoryId": '2022070517075639436760',
      "filter.types": [1]
    })
    try {

      try {
        let res = await api.goods.getGoodsPages(this.data.filter),
          data = res.data.ResData.Items || [];

        data.map(item => {
          if (item.MarketingTypes.toString().indexOf('2') != -1) {
            item.isSeckill = true;
          } else {
            item.isSeckill = false;
          }
          if (item.MarketingTypes.toString().indexOf('3') != -1) {
            item.isGroup = true;
          } else {
            item.isGroup = false;
          }
        })

        this.setData({
          youthList: data.splice(0, 4) || []
        })
        console.log(res, '年轻态商品列表')
      } catch (e) {
        console.log(e, '获取年轻态列表失败')
      }
    } catch (e) {
      console.log(e, '获取年轻态列表失败')
    }
  },

  // 获取皮肤管理师列表
  async getDoctors() {
    try {
      let res = await api.doctor.getDoctorList(''),
        data = res.data.ResData || [];
      console.log(res, '皮肤管理师列表')
      this.setData({
        skinList: data.splice(0, 10) || []
      })
    } catch (e) {
      console.log(e, '获取皮肤管理师列表失败')
    }
  },

  onShareAppMessage() {
    let userId = globalData.userInfo.UserId || '';
    console.log(`/pages/index/index?userId=${userId}`, '首页分享链接')
    return {
      title: 'TNTB超多好货等你来看',
      path: `/pages/index/index?userId=${userId}`
    }

  },

  // 首页banner跳转，暂时只有内部小程序跳转
  toBannerDetail(e) {
    let item = e.currentTarget.dataset.item;
    if (item.LinkUrl) {
      wx.navigateTo({
        url: item.LinkUrl,
      })
    }

  },

  // 获取拼团商品
  async getGroupList() {
    try {
      let res = await api.goods.getGroupList(this.data.filter2);
      console.log(res, '拼团商品列表')
      let groupList = res.data.ResData.Items;
      this.setData({
        groupList
      })
    } catch (e) {
      console.log(e, '获取拼团列表失败')
    }
  },
//   跳转公众号
  goAttention(){
    console.log("去公众号");
     wx.navigateTo({
      url: '/pages/index/attention/attention',
    })
  }

})